<?php

Route::get('/', function () {
  return view('welcome');
});

post('/login', function () {
  $credentials = Request::only('name', 'password');

  try {
    // attempt to verify the credentials and create a token for the user
    if (!$token = JWTAuth::attempt($credentials)) {

      return response()->json(['error' => 'invalid_credentials'], 401);
    }
  } catch (JWTException $e) {
    // something went wrong whilst attempting to encode the token
    return response()->json(['error' => 'could_not_create_token'], 500);
  }

  // all good so return the token
  return response()->json(compact('token'));
});


Route::group(['middleware' => 'jwt.auth'], function () {
  get('/api', function () {
    try {

      if (!$user = JWTAuth::parseToken()->authenticate()) {
        return response()->json(['user_not_found'], 404);
      }

    } catch (Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {

      return response()->json(['token_expired'], $e->getStatusCode());

    } catch (Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {

      return response()->json(['token_invalid'], $e->getStatusCode());

    } catch (Tymon\JWTAuth\Exceptions\JWTException $e) {

      return response()->json(['token_absent'], $e->getStatusCode());
    }

    // the token is valid and we have found the user via the sub claim
    return response()->json($user);
  });
});
